package com.chen10.cattle.service.impl;

import com.chen10.cattle.common.constants.RedisKeyConstants;
import com.chen10.cattle.common.enums.response.ErrorEnum;
import com.chen10.cattle.common.enums.friend.FriendshipStatusEnums;
import com.chen10.cattle.common.enums.game.UserOnlineStatus;
import com.chen10.cattle.common.exception.BusinessException;
import com.chen10.cattle.common.utils.RedisUtil;
import com.chen10.cattle.mapper.FriendshipMapper;
import com.chen10.cattle.model.dto.RemoveFriendDTO;
import com.chen10.cattle.model.vo.FriendVO;
import com.chen10.cattle.service.FriendService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {
    @Resource
    private FriendshipMapper friendshipMapper;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取好友列表
     * @param userId
     * @return
     */
    @Override
    public List<FriendVO> getFriendList(Integer userId) {
        if (userId == null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        List<FriendVO> friendVOList = friendshipMapper.getFriendList(userId);
        for(FriendVO friendVO:friendVOList) {
            String statusEnum = (String) redisUtil.get(RedisKeyConstants.REDIS_USER_STATUS_KEY_PREFIX + friendVO.getUserId());
            if (statusEnum == null) {
                statusEnum = UserOnlineStatus.OFFLINE.getDesc();
            }
            friendVO.setGameStatus(statusEnum);
        }

        return friendVOList;
    }

    @Override
    public void removeFriend(RemoveFriendDTO removeFriendDTO) {
        //校验参数
        if(removeFriendDTO==null){
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        Integer userId = removeFriendDTO.getUserid();
        Integer friendId = removeFriendDTO.getFriendId();
        if(userId==null||friendId==null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        //判断是否是好友
        if(!friendshipMapper.checkIsFriend(userId,friendId)){
            throw new BusinessException(ErrorEnum.REMOVE_ERROR_NOT_FRIEND_YET);
        }

        //更新好友状态
        friendshipMapper.updateStatus(userId,friendId,FriendshipStatusEnums.DELETED.getStatus());
    }
}
